package com.unlcn.ils.wms.app.controller.interceptor;

import cn.huiyunche.commons.domain.ResultDTO;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @Auther linbao
 * @Date 2017-10-14
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestURI = httpServletRequest.getRequestURI();
        String token = httpServletRequest.getParameter("token");
        if (StringUtils.isNotBlank(requestURI)
                && (requestURI.endsWith("loginForApp")
                || requestURI.endsWith("listWarehouseForApp"))) {
            return true;
        }
        HttpSession session = httpServletRequest.getSession();
        //
        if (Objects.equals(session, null)
                || StringUtils.isBlank(token)
                || Objects.equals(session.getAttribute(token), null)) {
            ResultDTO<Object> resultDTO = new ResultDTO<>(false);
            resultDTO.setMessageCode("404");
            resultDTO.setMessage("请登录");
            String responseJson = JSONObject.toJSONString(resultDTO);
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.getWriter().print(responseJson);
        } else {
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
